//
//  NearbyViewController.m
//  GYMWinners
//
//  Created by Logic Solutions on 3/11/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "NearbyViewController.h"
#import "FindGymAnnotion.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJSON.h"
#import "MBProgressHUD.h"
#import "BaseroutAPI.h"
#import "AppDelegate.h"

@implementation NearbyViewController
@synthesize locationManager;
@synthesize mapView;
@synthesize toolbar;

static double current_latitude = 0.0;
static double current_longitude = 0.0;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
     
    // Add map
    mapView.delegate=self;
    
    [mapView setZoomEnabled:YES];
    [mapView setScrollEnabled:YES];
    
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate=self; 
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    locationManager.distanceFilter=100.0f;
    [locationManager startUpdatingLocation];
    
    MKCoordinateSpan theSpan;  
    theSpan.latitudeDelta=0.02; 
    theSpan.longitudeDelta=0.02;
    
    MKCoordinateRegion theRegion; 
    theRegion.center=[[locationManager location] coordinate]; 
    theRegion.span=theSpan; 
    
    [mapView setRegion:theRegion]; 
    
    if([CLLocationManager locationServicesEnabled]){
        mapView.showsUserLocation=YES;
        [mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
    }
    
    
    // Add buttons
    MKUserTrackingBarButtonItem* trackingBarButton=[[MKUserTrackingBarButtonItem alloc] 
                                                    initWithMapView:self.mapView];
    UIBarButtonItem* refreshButton=[[UIBarButtonItem alloc] 
                                       initWithTitle:@"刷新" 
                                       style:UIBarButtonItemStyleBordered
                                       target:self 
                                       action:@selector(refresh)];
    UIBarButtonItem* addGymButton=[[UIBarButtonItem alloc] 
                                       initWithTitle:@"+健身馆" 
                                       style:UIBarButtonItemStyleBordered
                                       target:self 
                                       action:@selector(addGym)];
    
    [self.toolbar setItems: [NSArray arrayWithObjects:trackingBarButton,refreshButton,addGymButton,nil] animated:YES ];
    
    
}

- (void)viewDidUnload
{
    [self setMapView:nil];
    [super viewDidUnload];
}

- (void)dealloc {
    NSLog(@"dealloc nearvy view");
    mapView.delegate = nil;
    locationManager.delegate = nil;
    mapView.showsUserLocation = NO;
    [mapView removeAnnotations:mapView.annotations];
}

- (void)viewWillAppear:(BOOL)animated{
    
    NSLog(@"NearView viewWillAppear");
    [super viewWillAppear:animated];
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    mapView.delegate = self;
    locationManager.delegate = self;
    [locationManager startUpdatingLocation];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    
    NSLog(@"NearView viewWillDisappear");
    [super viewWillDisappear:animated];
    
    [locationManager stopUpdatingLocation];
    mapView.delegate = nil;
    locationManager.delegate = nil;
    
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


// called when phone location was changed
- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation{
    
    NSString* lat=[[NSString alloc] initWithFormat:@"%g",newLocation.coordinate.latitude];
    NSString* lng=[[NSString alloc] initWithFormat:@"%g",newLocation.coordinate.longitude];
    NSString* acc=[[NSString alloc] initWithFormat:@"%g",newLocation.horizontalAccuracy];
    NSLog(@"%@__%@__%@",lat,lng,acc);
    
    current_latitude = newLocation.coordinate.latitude;
    current_longitude = newLocation.coordinate.longitude;
    
    // update the map
    MKCoordinateSpan span;
    span.latitudeDelta=0.02;
    span.longitudeDelta=0.02;
    
    MKCoordinateRegion region;
    region.center=newLocation.coordinate;
    region.span=span;
    
    [mapView setRegion:region animated:YES];
    
}

#pragma mark - User-Defined Method
-(void) refresh{
    NSLog(@"refresh");
    [mapView removeAnnotations:mapView.annotations];
    [mapView setRegion:mapView.region animated:TRUE];    
    
    // asking for gym locations within updated map
    NSMutableDictionary *slist = [[NSMutableDictionary alloc] init];
    [slist setObject:[[BaseroutAPI sharedInstance] zGetVarEx:@"customerid"] forKey:@"cid"];
    [slist setObject:[NSString stringWithFormat:@"%g", current_latitude] forKey:@"lat"];
    [slist setObject:[NSString stringWithFormat:@"%g", current_longitude] forKey:@"lon"];
    [slist setObject:@"2000" forKey:@"radiusInMeter"];
    [self zSendServer:slist theTitle:@"请稍等" theCommand:@"/location/list"];  

}

-(void) addGym{
    NSLog(@"addGym");
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    
    // asking for gym locations within updated map
    NSMutableDictionary *slist = [[NSMutableDictionary alloc] init];
    [slist setObject:[[BaseroutAPI sharedInstance] zGetVarEx:@"customerid"] forKey:@"cid"];
    [slist setObject:[NSString stringWithFormat:@"%g", current_latitude] forKey:@"lat"];
    [slist setObject:[NSString stringWithFormat:@"%g", current_longitude] forKey:@"lon"];
    [slist setObject:@"2000" forKey:@"radiusInMeter"];
    [self zSendServer:slist theTitle:@"请稍等" theCommand:@"/location/list"];
}

-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    NSLog(@"==viewForAnnotation==>");
    
    if([annotation isKindOfClass:[FindGymAnnotion class]]){
        
        static NSString* defaultPinID=@"com.findGym.pin";
        MKPinAnnotationView* pinView=(MKPinAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
        
        if(!pinView){
            pinView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID];
        }
        
        pinView.annotation=annotation;
        pinView.pinColor=MKPinAnnotationColorRed;
        pinView.canShowCallout=YES;
        //pinView.animatesDrop = YES;
        pinView.draggable=YES;
        //[pinView setSelected:YES animated:YES];
        
        CLLocationCoordinate2D droppedAt=annotation.coordinate;
        NSLog(@"==started at %f,%f", droppedAt.latitude, droppedAt.longitude);  
        
        return pinView;        
    }
    return nil;    
}


-(void) mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState{
    
    if(oldState==MKAnnotationViewDragStateDragging){
        NSLog(@"MKAnnotationViewDragStateDragging");
    }
    if(newState==MKAnnotationViewDragStateEnding){
        CLLocationCoordinate2D droppedAt=view.annotation.coordinate;
        NSLog(@"==dropped at %f,%f", droppedAt.latitude, droppedAt.longitude);        
    }
}

#pragma mark - ASIFormDataRequest delegate

- (void)requestFinished:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    if (request.responseStatusCode == 200) {
        
        NSArray *all_old_anno = mapView.annotations;
        
        NSString *responseString = [request responseString];
        NSLog(@"responseString=[%@]", responseString);   
        NSArray *responseArr = [responseString JSONValue];
        for(int i=0; i< [responseArr count]; i++)
        {
            NSDictionary *gymloc = [responseArr objectAtIndex:i];
            NSString *gymname = [gymloc objectForKey:@"name"];
            //NSString *gymaddr = [gymloc objectForKey:@"address"];
            double gymlat = [[gymloc objectForKey:@"latitude"] doubleValue];
            double gymlog = [[gymloc objectForKey:@"longitude"] doubleValue];
            
            bool annoExist = false;
            for(int j =0; j< [all_old_anno count]; j++)
            {
                FindGymAnnotion* theAnno = [all_old_anno objectAtIndex:j];
                if( theAnno.coordinate.latitude == gymlat && theAnno.coordinate.longitude == gymlog )
                {
                    NSLog(@"anno exist, %g_%g", gymlat, gymlog);
                    annoExist = true;
                    break;
                }
            }
            
            if( !annoExist )
            {
                CLLocationCoordinate2D cl;
                cl.latitude = gymlat;
                cl.longitude = gymlog;
                FindGymAnnotion* gymAnno=[[FindGymAnnotion alloc] initWithCoordinate:cl]; 
                gymAnno.title = gymname;
                [mapView addAnnotation:gymAnno];
            }
        }
        
        //[mapView removeAnnotations:all_old_anno];
        
    } else {
        NSLog(@"Unexpected error");  
        [[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"通讯失败"];
    }
    
}

- (void)requestFailed:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    NSError *error = [request error];
    NSLog(@"Error=%@", error.localizedDescription);   
    
    [[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"通讯失败"];
}


@end
